Skip to content
This repository has been archived by the owner on Sep 1, 2020. It is now read-only.

Latest commit

 

History

History
54 lines (50 loc) · 1.38 KB

6.6 - Channel.md

File metadata and controls

54 lines (50 loc) · 1.38 KB

Channel

Swoole-1.9.0新增了一个新的内存数据结构Channel,用于实现高性能的进程间通信,底层基于共享内存+Mutex互斥锁实现,可实现用户态的高性能内存队列。

  • Channel可用于多进程环境下,底层在读取写入时会自动加锁,应用层不需要担心数据同步问题
  • 必须在父进程内创建才可以在子进程内使用

Channel不受PHPmemory_limit控制

使用示例:

$chan = new Swoole\Channel(1024 * 256);
$n = 100000;
$bytes = 0;
if (pcntl_fork() > 0)
{
    echo "Father\n";
    for ($i = 0; $i < $n; $i++)
    {
        $data = str_repeat('A', rand(100, 200));
        if ($chan->push($data) === false)
        {
            echo "channel full\n";
            usleep(1000);
            $i--;
            continue;
        }
        $bytes += strlen($data);
//        echo "#$i\tpush ".strlen($data)." bytes\n";
    }
    echo "total push bytes: $bytes\n";
    var_dump($chan->stats());
}
else
{
    echo "Child\n";
    for ($i = 0; $i < $n; $i++)
    {
        $data = $chan->pop();
        if ($data === false)
        {
            echo "channel empty\n";
            usleep(1000);
            $i--;
            continue;
        }
        $bytes += strlen($data);
//        echo "#$i\tpop " . strlen($data) . " bytes\n";
    }
    echo "total pop bytes: $bytes\n";
    var_dump($chan->stats());
}